import { _g, _circle, _text } from '../svg.js'
import { pointsPath } from '../path.js'
import { rayMix } from '../../math/arrayMix.js'
import { plainMatrix } from '../../math/index.js'
import { polarPoints, polarGridPoints } from '../../algorithm/polar.js'

// 极坐标
export const _polar = (options) => {
    let {
        width = 800,
        height = 600,
        r = 100,
        n = 12,
        a = 0,
        props = {},
        crossPoints = {},
        labels
    } = options
    let o = [width / 2, height / 2]
    let m = Math.ceil((width > height ? width : height) / r / 2)
    let circles = Array.from({ length: m + 1 }, (_, i) => _circle({ o, r: r * i }, {
        'stroke-dasharray': 4,
    }))
    let children = [circles]

    // 最外层点
    let points = polarPoints({
        o,
        r: r * m,
        n,
        a
    })

    let pgp = []

    if (crossPoints || labels) {
        pgp = polarGridPoints({
            o,
            r,
            n,
            a,
            m
        })
        pgp = plainMatrix(pgp)
    }


    // 交叉点
    if (crossPoints) {


        children.push(...pgp.map(t => _circle({
            o: t,
            r: 2
        }, {
            fill: 'red',
            stroke: 'none'
        })))



    }

    if (labels) {
        children.push(...pgp.map((t, i) => _text(
            [...t, i]
            , {
                'font-size': 12,
                'text-anchor': 'middle',
                'dominant-baseline': 'middle',
                stroke: 'gray'
            })))
    }


    // 对角点  排序
    let rps = rayMix(o, points)


    // 轴
    let axis = pointsPath({
        points: rps,
        closed: false,
        broken: true
    }, {
        'stroke-dasharray': 4,
    })
    children.push(axis)

    let g = _g(children, {
        name: 'polar',
        fill: 'none',
        stroke: 'black',
        ...props
    })
    return g
}